<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>标签横向瀑布流</title> 
    <style>
        body{
            padding-left: 100px;
        }
        ul{
            list-style: none;
            font-size: 14px;
            width: 450px;
            padding: 0;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }
        li{
            color: lightcoral;
            display: inline-flex;
            white-space: nowrap;
        }
        span{
            background: #ddd;
            border-radius: 8px;
            padding: 5px 10px;
        }
    </style>
</head>
<body>
    <ul></ul>
    <script>
        buildTag();
        setSpan();

        function setSpan(){
            let gap = 10;
            let ul = document.querySelector('ul');
            let ulWidth = ul.offsetWidth;            
            let lasts = Array.from(ul.children).map(t => { return {el: t, width: t.offsetWidth } });

            let row = [];
            let rowIndex = 0;
            
            buildRowHead(row, rowIndex, lasts);

            while(lasts.length){
                //剩余元素中找
                let fitItemIndex = lasts.findIndex(t => t.width + row[rowIndex].width + gap < ulWidth);
                if(fitItemIndex != -1){
                    lasts[fitItemIndex].el.style.order = rowIndex;
                    row[rowIndex].width += lasts[fitItemIndex].width + gap;
                    lasts.splice(fitItemIndex, 1);
                }
                else{
                    rowIndex++;
                    buildRowHead(row, rowIndex, lasts);
                }
            }
            console.log(row);
        }

        function buildRowHead(row, rowIndex, lasts){
            row[rowIndex] = {width:0};
            row[rowIndex].width += lasts[0].width;
            lasts[0].el.style.order = rowIndex;
            lasts.splice(0, 1);
        }

        function buildTag(){
            let pattern = new RegExp("[\u4E00-\u9FA5]+");
            let a = ['客开赋能机器人开发流程','后端运维工程开发环境','Red Tea',
            '交易快照:服务内容不符时可作为判断依据','商户信息有误，我要上报我要申请退款',
            '您点错了，这个订单不是外卖.分店可否使用','团购券如何使用美团券能否叠加使用','订单是否为外卖',
            'Milk开发环境','测试环境','前端','java','环境','开发环境'];
            let ul = document.querySelector('ul');
            a.map((t,i) => {
                ul.insertAdjacentHTML('beforeend',`<li><span>${i+1}.${t}</span></li>`)
            })
        }
    </script>
</body>
</html>